package com.whjz.common;

import java.util.Optional;
import java.util.concurrent.*;

/**
 * 限时获取器
 * @param <T> 结果类
 */
public interface TimedGetter<T> {
    /**
     * 获取
     * @param timeoutInMills 限时,单位毫秒,0表示不限制
     * @return 结果
     * @throws TimeoutException 超时抛出
     */
    default T get(long timeoutInMills) throws TimeoutException{
        BlockingQueue<Optional<T>> queue = new LinkedBlockingDeque<>();

        //执行
        new Thread(() -> {
            T value = null;
            try {
                value = doGet();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                queue.put(Optional.ofNullable(value));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        try {
            Optional<T> value = queue.poll(timeoutInMills, TimeUnit.MILLISECONDS);
            if (value == null) {
                throw new TimeoutException();
            }
            return value.orElse(null);
        } catch (InterruptedException e) {
            throw new RuntimeException();
        }
    }

    /**
     * 执行获取
     */
    T doGet() throws Exception;
}
